#include "Socket.hpp"
#include "comm.hpp"
#include "Protocol.hpp"
#include <iostream>
#include <string>
#include <memory>

using namespace SocketModule;

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc <<" server_ip server_port" << std::endl;
}

void GetData(int *x, int *y, char *oper)
{
    std::cout << "please enter x: ";
    std::cin >> *x;
    std::cout << "please enter y: ";
    std::cin >> *y;
    std::cout << "please enter oper: ";
    std::cin >> *oper;
}

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client->BuildTcpClientSocket();
    if(client->Connect(server_ip, server_port) != 0)
    {
        // 连接失败
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERR);
    }

    std::unique_ptr<Protocol> pro = std::make_unique<Protocol>();
    std::string resp_buff;
    // 连接成功
    while(1)
    {
        // 获取数据
        int x, y;
        char oper;
        GetData(&x, &y, &oper);

        // 构建一个请求
        std::string req_str = pro->BuildRequestString(x, y, oper);
        // std::cout << "--------------encode req string----------------" << std::endl;
        // std::cout << req_str << std::endl;
        // 发送
        client->Send(req_str);

        // 获取应答
        Response resp;
        bool ret = pro->GetResponse(client, resp_buff, &resp);
        if(!ret) break;

        //显示结果
        resp.ShowResult();
    }

    client->Close();
    
    return 0;
}